package com.sfac.day03.modules.test.controller;

import com.github.pagehelper.Page;
import com.sfac.day03.modules.common.entity.ResultEntity;
import com.sfac.day03.modules.common.entity.SearchBean;
import com.sfac.day03.modules.test.entity.Student;
import com.sfac.day03.modules.test.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
//Controller与RestController的区别:前者return回去为json,h后者需要在每个方法上加responsebody
@RestController
@RequestMapping("/api")
public class StudentController {
    @Autowired
    private StudentService studentService;

    /**
     * 127.0.0.1/api/student ---- post
     * {"studentName":"yhq","age":22,"sex":"male"}
     * {"studentName":"yhq","age":22,"sex":"male","studentCard":{"cardNo":"2021020101"}}
     */
    @PostMapping(value = "/student", consumes = "application/json")
    public ResultEntity<Student> insertStudent(@RequestBody Student student) {
        return studentService.insertStudentForJpa(student);
    }

    /**
     * 127.0.0.1/api/student ---- put
     * {"id":3,"studentName":"yhq1","age":22,"sex":"male"}
     */
    @PutMapping(value = "/student", consumes = "application/json")
    public ResultEntity<Student> updateStudent(@RequestBody Student student) {
        return studentService.updateStudent(student);
    }

    /**
     * 127.0.0.1/api/student/2 ---- delete
     */
    @DeleteMapping("/student/{id}")
    public ResultEntity<Student> deleteStudent(@PathVariable int id) {
        return studentService.deleteStudent(id);
    }

    /**
     * 127.0.0.1/api/student?studentName=yhq1&age=22 ---- get
     */
    @GetMapping("/student")
    public Student findByStudentNameAndAge(@RequestParam String studentName,
                                           @RequestParam int age) {
        return studentService.findByStudentNameAndAge(studentName, age);
    }

    /**
     * 127.0.0.1/api/students ---- post
     * {"currentPage":1, "pageSize":5, "orderBy":"student_name",
     * "direction":"desc", "keyword": "y"}
     */
    @PostMapping(value = "/students", consumes = "application/json")
    public Page<Student> getStudentsBySearchBean(@RequestBody SearchBean searchBean) {
        return studentService.getStudentsBySearchBean(searchBean);
    }

    /**
     * 127.0.0.1/api/student/v2?id=3&studentName=yhq ---- get
     */
    @GetMapping("/student/v2")
    public Student getStudentByIdAndStudentName(@RequestParam int id,
                                                @RequestParam String studentName) {
        return studentService.getStudentByIdAndStudentName(id, studentName);
    }
}

